<template>
  <div class="vocabulary-form-page" :class="{ 'dark-theme': isDarkMode }">
    <!-- 头部区域 -->
    <header class="app-header border-b">
      <div class="container">
        <h1 class="text-2xl font-bold text-primary title-center">词汇本提交</h1>
        <div class="header-actions flex justify-center gap-3 mt-2">
          <el-button 
            type="default" 
            size="small" 
            @click="goToHome"
            class="home-btn"
            title="返回主页"
          >
            <el-icon class="mr-1"><ArrowLeft /></el-icon>
            返回主页
          </el-button>
          <el-button 
            circle 
            size="small" 
            @click="toggleTheme"
            class="theme-btn"
            title="切换主题"
          >
            <span>{{ isDarkMode ? '🌞' : '🌙' }}</span>
          </el-button>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-container">
      <div class="form-card bg-card dark:bg-dark-card rounded-xl border shadow-md p-6 md:p-8 max-w-3xl mx-auto transform transition-all duration-300 hover:shadow-lg">
        <div class="form-header mb-6">
          <h2 class="form-title text-2xl font-semibold mb-2">词汇本信息录入</h2>
          <p class="form-subtitle text-gray-500 dark:text-gray-400">请按照格式要求输入词汇信息，提交后可在词汇模块查看</p>
        </div>
        
        <el-form 
          ref="vocabForm" 
          :model="formData" 
          :rules="formRules" 
          class="vocab-form"
          label-width="120px"
        >
          <!-- 词汇书名称 -->
          <el-form-item label="词汇书名称" prop="bookName" class="form-item">
            <el-input 
              v-model="formData.bookName" 
              placeholder="请输入词汇书名称（如：高中英语核心词汇）"
              class="input-field"
            ></el-input>
          </el-form-item>

          <!-- 词汇输入区域 -->
          <el-form-item label="单词列表" prop="vocabularies" class="form-item">
            <el-input
              v-model="formData.vocabularies"
              type="textarea"
              rows="10"
              placeholder="请严格按照顺序输入：单词;词性;词意;例句。（每个单词以句号结尾，分号分隔各部分）"
              class="textarea-field"
            ></el-input>
            
            <!-- 格式说明（优化输入顺序和示例） -->
            <div class="format-hint mt-3 p-4 bg-primary/5 dark:bg-primary/10 rounded-lg text-sm border border-primary/20">
              <p class="font-medium mb-2 flex items-center">
                <el-icon class="mr-1.5 text-primary" size="16"><InfoFilled /></el-icon>
                输入格式说明（<span class="text-danger">顺序必须严格遵守</span>）
              </p>
              <ul class="list-disc pl-6 space-y-2">
                <li>每个单词项以 <span class="text-primary font-medium">句号(。)</span> 结束</li>
                <li>单词信息必须按以下顺序用 <span class="text-primary font-medium">分号(;)</span> 分隔：
                  <ol class="list-decimal pl-6 mt-1 space-y-1">
                    <li><code>单词(spell)</code>：单词的拼写（如：apple）</li>
                    <li><code>词性(category)</code>：单词的词性（如：名词、动词）</li>
                    <li><code>词意(briefDefinitions)</code>：单词的中文释义（如：苹果）</li>
                    <li><code>例句(example)</code>：包含该单词的例句（如：This is an apple.）</li>
                  </ol>
                </li>
                <li>
                  正确示例：
                  <div class="mt-1 p-2 bg-gray-100 dark:bg-gray-800 rounded text-xs font-mono">
                    apple;<span class="text-secondary">名词</span>;<span class="text-secondary">苹果</span>;<span class="text-secondary">This is an apple。</span><br>
                    run;<span class="text-secondary">动词</span>;<span class="text-secondary">跑</span>;<span class="text-secondary">He can run fast。</span>
                  </div>
                </li>
                <li class="text-danger">错误提示：缺少分号、顺序颠倒或未以句号结尾都会导致提交失败</li>
              </ul>
            </div>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item class="form-actions pt-4">
            <div class="button-group flex flex-wrap gap-3 justify-center">
              <el-button 
                type="primary" 
                @click="handleSubmit"
                class="submit-btn px-8 py-2.5 text-base"
                :loading="isSubmitting"
              >
                <el-icon class="mr-2" size="18" v-if="!isSubmitting"><Upload /></el-icon>
                <el-icon class="mr-2" size="18" v-if="isSubmitting"><Loading /></el-icon>
                {{ isSubmitting ? '提交中...' : '提交词汇本' }}
              </el-button>
              <el-button 
                type="default" 
                @click="handleReset"
                class="reset-btn px-8 py-2.5 text-base"
                :disabled="isSubmitting"
              >
                <el-icon class="mr-2" size="18"><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 提交结果反馈 -->
      <el-dialog 
        v-model="showResultDialog" 
        title="提交结果" 
        width="500px"
        :closable="false"
        :border="false"
        class="result-dialog"
      >
        <div class="result-content py-4">
          <div v-if="submitSuccess" class="success-result text-center">
            <div class="success-icon-wrapper w-16 h-16 bg-success/10 dark:bg-success/20 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon class="success-icon text-success" size="32"><Check /></el-icon>
            </div>
            <h3 class="result-title text-xl font-semibold mb-2">提交成功！</h3>
            <p class="result-desc text-gray-600 dark:text-gray-300 mb-3">词汇本 "{{ formData.bookName }}" 已成功创建</p>
            <p class="result-stats text-primary font-medium">共添加 {{ parsedWordsCount }} 个单词</p>
          </div>
          <div v-else class="error-result text-center">
            <div class="error-icon-wrapper w-16 h-16 bg-error/10 dark:bg-error/20 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon class="error-icon text-error" size="32"><Close /></el-icon>
            </div>
            <h3 class="result-title text-xl font-semibold mb-2">提交失败</h3>
            <p class="result-desc text-gray-600 dark:text-gray-300">{{ submitMessage }}</p>
          </div>
        </div>
        <template #footer>
          <el-button type="primary" @click="showResultDialog = false" class="w-full md:w-auto">确定</el-button>
        </template>
      </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { Check, Close, Upload, Refresh, InfoFilled, ArrowLeft, Loading } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import vocabularyApi from '@/views/subjects/english/pages/vocabulary-study/script/vocabulary-js/vocabularyInsert.js';

// 状态管理
const isDarkMode = ref(false);
const isSubmitting = ref(false);
const vocabForm = ref(null);

// 表单数据
const formData = reactive({
  bookName: '',
  vocabularies: ''
});

// 提交结果
const showResultDialog = ref(false);
const submitSuccess = ref(false);
const submitMessage = ref('');
const parsedWordsCount = ref(0);

// 返回主页
const goToHome = () => {
  ElMessage.info('返回主页');
};

// 验证函数
const validateVocabFormat = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入单词列表'));
  }
  
  const items = value.split('。').map(item => item.trim()).filter(item => item);
  
  if (items.length === 0) {
    return callback(new Error('请输入有效的单词信息'));
  }
  
  for (let i = 0; i < items.length; i++) {
    if (!items[i].includes(';')) {
      return callback(new Error(`第 ${i+1} 个单词项格式不正确，缺少分号分隔符`));
    }
    const parts = items[i].split(';');
    if (parts.length < 4) {
      return callback(new Error(`第 ${i+1} 个单词项格式不完整，需包含：单词;词性;词意;例句`));
    }
  }
  
  callback();
};

// 表单规则
const formRules = reactive({
  bookName: [
    { required: true, message: '请输入词汇书名称', trigger: 'blur' },
    { max: 50, message: '名称长度不能超过50个字符', trigger: 'blur' }
  ],
  vocabularies: [
    { required: true, message: '请输入单词列表', trigger: 'blur' },
    { validator: validateVocabFormat, trigger: 'blur' }
  ]
});

// 解析单词为后端需要的格式
const parseVocabularies = (vocabString) => {
  try {
    const items = vocabString.split('。')
      .map(item => item.trim())
      .filter(item => item);

    if (items.length === 0) {
      throw new Error('未找到有效的单词信息');
    }

    const words = items.map((item, index) => {
      const parts = item.split(';').map(part => part.trim());
      
      if (parts.length < 4) {
        throw new Error(`第 ${index + 1} 个单词格式不完整（需包含：单词;词性;词意;例句）`);
      }

      return {
        spell: parts[0],          // 单词拼写
        category: parts[1],       // 词性
        briefDefinitions: parts[2], // 词意
        example: parts[3],        // 例句
        pronunciation: '',        // 音标（可选）
        chinese: parts[2]         // 中文提示
      };
    });

    return { success: true, data: words };
  } catch (error) {
    return { success: false, message: error.message };
  }
};

// 提交处理
const handleSubmit = () => {
  vocabForm.value.validate((valid) => {
    if (valid) {
      isSubmitting.value = true; // 显示加载状态
      
      // 解析单词数据
      const parseResult = parseVocabularies(formData.vocabularies);
      if (!parseResult.success) {
        isSubmitting.value = false;
        submitSuccess.value = false;
        submitMessage.value = parseResult.message;
        showResultDialog.value = true;
        return;
      }
      const words = parseResult.data;
      parsedWordsCount.value = words.length;

      // 提交数据到后端
      vocabularyApi.createVocabularyBook(formData.bookName)
        .then((book) => {
          return vocabularyApi.addWordsToBook({
            bookId: book.id,
            words: words
          });
        })
        .then(() => {
          submitSuccess.value = true;
          submitMessage.value = '';
          showResultDialog.value = true;
        })
        .catch((error) => {
          submitSuccess.value = false;
          submitMessage.value = error.message || '提交失败，请稍后重试';
          showResultDialog.value = true;
        })
        .finally(() => {
          isSubmitting.value = false;
        });
    }
  });
};

// 重置表单
const handleReset = () => {
  vocabForm.value.resetFields();
  submitSuccess.value = false;
  submitMessage.value = '';
};

// 主题切换
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value;
  document.documentElement.classList.toggle('dark-theme', isDarkMode.value);
  localStorage.setItem('systemTheme', isDarkMode.value ? 'dark' : 'light');
};

// 初始化主题
const initTheme = () => {
  const savedTheme = localStorage.getItem('systemTheme');
  if (savedTheme === 'dark') {
    toggleTheme();
  }
};

initTheme();
</script>

<style scoped>
:root {
  --primary: #3b82f6;
  --primary-light: #60a5fa;
  --primary-dark: #2563eb;
  --primary-bg: rgba(59, 130, 246, 0.05);
  --success: #10b981;
  --error: #ef4444;
  --text-light: #1f2937;
  --text-light-secondary: #4b5563;
  --text-dark: #f3f4f6;
  --text-dark-secondary: #d1d5db;
  --bg-light: #f9fafb;
  --bg-dark: #111827;
  --card-light: #ffffff;
  --card-dark: #1f2937;
  --border: #e5e7eb;
  --border-dark: #374151;
  --hover: #f3f4f6;
  --hover-dark: #374151;
  --active: rgba(59, 130, 246, 0.1);
  --transition: 0.3s ease;
  --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
  --shadow-hover: 0 10px 15px -3px rgba(0, 0, 0, 0.08), 0 4px 6px -2px rgba(0, 0, 0, 0.04);
}

.dark-theme {
  --text-light: #f3f4f6;
  --text-light-secondary: #d1d5db;
  --text-dark: #1f2937;
  --bg-light: #111827;
  --bg-dark: #0f172a;
  --card-light: #1f2937;
  --card-dark: #111827;
  --border: #374151;
  --hover: #374151;
  --active: rgba(59, 130, 246, 0.2);
  --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2), 0 2px 4px -1px rgba(0, 0, 0, 0.1);
  --shadow-hover: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.15);
}

/* 修复白色主题提交按钮字体显示问题 */
.submit-btn {
  background-color: var(--primary) !important;
  border-color: var(--primary) !important;
  color: #ffffff !important; /* 强制白色字体 */
  transition: all var(--transition);
  border-radius: 8px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
}

.submit-btn:hover {
  background-color: var(--primary-dark) !important;
  border-color: var(--primary-dark) !important;
  color: #ffffff !important; /* 保持白色字体 */
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
}

/* 格式说明中的样式优化 */
.format-hint .text-secondary {
  color: var(--text-light-secondary);
  font-weight: normal;
}

.format-hint .text-danger {
  color: var(--error);
  font-weight: 500;
}

/* 基础样式 */
* {
  font-family: "行文楷体", "KaiTi", "STKaiti", serif !important;
}

.vocabulary-form-page {
  min-height: 100vh;
  background-color: var(--bg-light);
  color: var(--text-light);
  transition: background-color var(--transition), color var(--transition);
  padding-bottom: 60px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
  text-align: center;
}

.app-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: var(--card-light);
  border-color: var(--border);
  transition: all var(--transition);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  padding: 12px 0;
}

.title-center {
  margin: 0 auto 8px;
  color: var(--primary);
  transition: color var(--transition);
}

.header-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

.text-primary {
  color: var(--primary);
  transition: color var(--transition);
}

.home-btn {
  background-color: var(--primary-bg);
  color: var(--primary);
  border-color: var(--primary);
  transition: all var(--transition);
}

.home-btn:hover {
  background-color: var(--active);
  color: var(--primary-dark);
  border-color: var(--primary-dark);
}

.theme-btn {
  transition: transform var(--transition), background-color var(--transition);
  background-color: var(--primary-bg);
  color: var(--primary);
  border: 1px solid var(--primary);
}

.theme-btn:hover {
  transform: scale(1.1);
  background-color: var(--active);
}

.main-container {
  padding: 130px 20px 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.form-card {
  border-color: var(--border);
  transition: all var(--transition);
  background-color: var(--card-light);
  margin-top: 20px;
}

.form-header {
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border);
}

.form-title {
  color: var(--text-light);
  transition: color var(--transition);
}

.form-subtitle {
  font-size: 0.95rem;
  transition: color var(--transition);
}

.form-item {
  margin-bottom: 24px;
  transition: all var(--transition);
}

.el-form-item__label {
  font-weight: 500;
  color: var(--text-light);
  transition: color var(--transition);
  padding: 0 0 8px 0;
}

.input-field, .textarea-field {
  width: 100%;
  transition: all var(--transition);
  border-color: var(--border);
  border-radius: 8px;
  font-size: 15px;
}

.input-field:focus-within, .textarea-field:focus-within {
  border-color: var(--primary);
  box-shadow: 0 0 0 3px var(--primary-bg);
}

.textarea-field {
  resize: vertical;
  min-height: 180px;
  line-height: 1.6;
}

.format-hint {
  color: var(--text-light-secondary);
  transition: all var(--transition);
  line-height: 1.6;
}

.format-hint code {
  font-family: 'Consolas', monospace !important;
  transition: background-color var(--transition);
}

.form-actions {
  margin-top: 30px;
  transition: all var(--transition);
}

.button-group {
  width: 100%;
}

.reset-btn {
  background-color: var(--card-light);
  border-color: var(--border);
  color: var(--text-light);
  transition: all var(--transition);
  border-radius: 8px;
  font-weight: 500;
}

.reset-btn:hover {
  background-color: var(--hover);
  border-color: var(--border);
  transform: translateY(-2px);
}

.result-dialog {
  --el-dialog-bg-color: var(--card-light);
  --el-dialog-border-color: var(--border);
}

.result-content {
  color: var(--text-light);
  transition: color var(--transition);
}

.result-title {
  color: var(--text-light);
  transition: color var(--transition);
}

.result-desc {
  line-height: 1.6;
}

.result-stats {
  font-size: 15px;
}

.success-icon-wrapper, .error-icon-wrapper {
  transition: all var(--transition);
}

/* 响应式样式 */
@media (max-width: 768px) {
  .form-card {
    padding: 40px 16px;
    margin: 10px;
  }
  
  .form-title {
    font-size: 1.5rem;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .el-form-item__label {
    display: block;
    padding-bottom: 8px;
  }
  
  .button-group {
    flex-direction: column;
  }
  
  .submit-btn, .reset-btn {
    width: 100%;
  }
  
  .main-container {
    padding: 120px 10px 10px;
  }
  
  .header-actions {
    flex-wrap: wrap;
    padding: 0 10px;
  }
}
</style>
